(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('lfe.ppfRepayment.createRejectController', createRejectController);
	createRejectController.$inject = [ '$q', '$filter', '$scope', 'Constants', 'formatService', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'ppfRepaymentService', 'dateService', "arithService", 'commonService'];
	function createRejectController($q, $filter, $scope, Constants, formatService, modalService, gridService, layoutConfig, validatorConfig, authService, ppfRepaymentService, dateService, arithService, commonService) {
		var ctrl = this, params = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.ppfRepaymentLoad = {};
		
		ctrl.init = function() {
			if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.loansCfg.tableConfigs.table.validatorConfig = ctrl.validatorConfig.ppfRepayments;
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.loansCfg.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.ppfRepaymentLoad.ppfRepayments';
			function rowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedPpfRepayments = selectedRows;
			}
			ppfRepaymentService.getCurrencyOptions().then(function(response) {
				ctrl.currencyOptions = response.data;
				authService.createReject(params).then(function(response) {
					if (response.data && response.data.model && response.data.task) {
						ctrl.ppfRepaymentLoad= response.data.model;
						ctrl.ppfRepaymentLoad.taskId = response.data.task.taskId;
					}
				});
			});
		};
		
		var watcher = $scope.$watch('vm.ppfRepaymentLoad.ppfRepayments.length', function(modelValue) {
			if(modelValue || modelValue == 0){
				ctrl.ppfRepaymentLoad.payTotalAmount = calPayTotalAmount(ctrl.ppfRepaymentLoad.ppfRepayments);
				ctrl.ppfRepaymentLoad.totalLoanAmt = calTotalLoanAmt(ctrl.ppfRepaymentLoad.ppfRepayments);
				ctrl.ppfRepaymentLoad.numOfPayments = ctrl.ppfRepaymentLoad.ppfRepayments.length;
			}
		});
		$scope.$on('$destroy', function() {
			(watcher || angular.noop)();
		});
		
		ctrl.changeInvoicepayAmt = function(value, formCtrl, isInitialized){
			if(!isInitialized){
				ctrl.ppfRepaymentLoad.payTotalAmount = calPayTotalAmount(ctrl.ppfRepaymentLoad.ppfRepayments);
			}
		};
		
		function calPayTotalAmount(ppfRepayments){
			var payTotalAmount = 0;
			angular.forEach(ppfRepayments, function(value, key) {
				payTotalAmount = parseFloat(arithService.add(payTotalAmount, value.paymentAmount));
			});
			return payTotalAmount;
		};
		
		function calTotalLoanAmt(ppfRepayments){
			var totalLoanAmt = 0;
			angular.forEach(ppfRepayments, function(value, key) {
				totalLoanAmt = parseFloat(arithService.add(totalLoanAmt, value.loanOutAmount));
			});
			return totalLoanAmt;
		};
		
		ctrl.addLoan = function(){
			var deferred = $q.defer(), params = {};
			var promise = deferred.promise;
			if(!ctrl.ppfRepaymentLoad.companyCode){
				deferred.reject();
			}else{
				ppfRepaymentService.getPpfRepaymentsInProcing().then(function(response) {
					params.filterLoanIds = [];
					angular.forEach(response.data, function(ppfRepayment, index) {
						params.filterLoanIds.push($filter('encode')(ppfRepayment.loanId));
					});
					params.obligorCode = $filter('encode')(ctrl.ppfRepaymentLoad.companyCode);
					params.loanCcy = ctrl.ppfRepaymentLoad.payCcy;
					angular.forEach(ctrl.ppfRepaymentLoad.ppfRepayments, function(loan, index) {
						params.filterLoanIds.push($filter('encode')(loan.loanId));
					});
					params.prodType = 'PPF';
					params.multiSelect = 'true';
					params.loanStatusList = ['N', 'P'];//DISBURSED/Pastdue
					params.lockFlag = 'N';
					params.loanCcyReadonly = true;
					params.effectiveDateCheckWithBizDate = true;
					modalService.openCustomDialogs({
						'dialogsModule' : 'cls.lookupLoanList',
						'title' : 'title.dialogs.lookup',
						'params' : params,
						'btnCallback' : {
							'ok' : function(selectedRows) {
								if (!selectedRows || selectedRows.length == 0) {
									modalService.openErrorDialogs({
										messages : [ 'title.dialogs.info.norecsel' ]
									});
								}else{
									angular.forEach(selectedRows, function(loan, index) {
										var _ppfRepayment = {};
										_ppfRepayment.loanId = loan.loanInfo.loanId;
										_ppfRepayment.loanEffectiveDate = loan.loanInfo.effectiveDate;
										_ppfRepayment.loanMaturityDate = loan.loanInfo.maturityDate;
										_ppfRepayment.loanCcy = loan.loanInfo.loanCcy;
										_ppfRepayment.loanAmount = loan.loanInfo.loanAmt;
										_ppfRepayment.loanOutAmount = loan.loanExt.princOutstdAmt;
										_ppfRepayment.paymentAmount = loan.loanExt.princOutstdAmt;
										_ppfRepayment.dataStatus = "C";
										ctrl.ppfRepaymentLoad.ppfRepayments.push(_ppfRepayment);
									});
								}
								deferred.reject();
							},
							'close' : function(){
								deferred.reject();
							}
						}
					});
				});
			}
			return promise;
		};
		
		/*ctrl.removeLoan = function(row){
			if (!ctrl.selectedPpfRepayments || ctrl.selectedPpfRepayments.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.info.norecsel' ]
				});
				return false;
			}
			angular.forEach(ctrl.selectedPpfRepayments, function(selectedPpfRepayment, key) {
				angular.forEach(ctrl.ppfRepaymentLoad.ppfRepayments, function(ppfRepayment, index) {
					if (ppfRepayment.$$hashKey == selectedPpfRepayment.$$hashKey) {
						ctrl.ppfRepaymentLoad.ppfRepayments.splice(index, 1);
					}
				});
			});
		};*/

		ctrl.createRejectSave = function() {
			if (!ctrl.ppfRepaymentLoad.ppfRepayments || ctrl.ppfRepaymentLoad.ppfRepayments.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.loan.norecsel' ]
				});
				return false;
			}
			return authService.createRejectSave(ctrl.ppfRepaymentLoad).then(saveSuccessful, saveFailed);
		};

		ctrl.createRejectSubmit = function() {
			if (!ctrl.ppfRepaymentLoad.ppfRepayments || ctrl.ppfRepaymentLoad.ppfRepayments.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.loan.norecsel' ]
				});
				return false;
			}
			return authService.createRejectSubmit(ctrl.ppfRepaymentLoad).then(submitSuccessful, submitFailed);
		};
		
		ctrl.createRejectCancel = function() {
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.cancel', args : [ctrl.ppfRepaymentLoad.primaryKey]} ],
				'btnCallback' : {
					'ok' : function() {
						authService.createRejectCancel(ctrl.ppfRepaymentLoad).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('lfe.workflow.wfTxn.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'lfe.workflow.wfTxn.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.ppfrepayment.create',
					'state' : 'lfe.ppfRepayment.create',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				angular.extend(ctrl.ppfRepaymentLoad, response.data.model);
			}else if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.cancel' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('lfe.workflow.wfTxn.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'lfe.workflow.wfTxn.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.ppfrepayment.create',
					'state' : 'lfe.ppfRepayment.create',
					'params' : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}	
		
	}
})(angular);
